<template>
  <div class="dashboard-container">
    <!-- 左右结构图表 -->
    <div class="chart-row">
      <!-- 左侧折线图 -->
      <div class="chart-card left-chart">
        <div class="chart-header">
          <h3>销售额（按时间）<span class="unit">单位：元</span></h3>
          <el-select 
            v-model="timeRange" 
            placeholder="按月份"
            class="time-select"
            @change="handleTimeRangeChange">
            <el-option label="按月份" value="month" />
            <el-option label="按年份" value="year" />
          </el-select>
        </div>
        <div ref="trendChart" class="chart"></div>
      </div>

      <!-- 右侧环形图 -->
      <div class="chart-card right-chart">
        <h3>销售额（按分类）<span class="unit">单位：元</span></h3>
        <div class="date-picker-container">
          <el-date-picker
            v-model="dateRange"
            type="daterange"
            range-separator="至"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
            value-format="YYYY-MM-DD"
            @change="handleDateChange"
            class="date-picker"
          />
        </div>
        <div ref="categoryChart" class="chart"></div>
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted } from 'vue'
import * as echarts from 'echarts'
import type { DashboardDTO } from './types'
import { getDashboardData } from '@/api/dashboard'

// 图表引用
const trendChart = ref<HTMLElement>()
const categoryChart = ref<HTMLElement>()

// 筛选状态
const timeRange = ref<'month' | 'year'>('month')
const dateRange = ref(['2024-08-01', '2024-08-08'])
const dashboardData = ref<DashboardDTO>()

// 图表实例
let trendInstance: echarts.ECharts
let categoryInstance: echarts.ECharts

onMounted(() => {
  trendInstance = echarts.init(trendChart.value!)
  categoryInstance = echarts.init(categoryChart.value!)

  fetchDashboardData()
  
  // renderTrendChart('month')
  // renderCategoryChart()
  
  window.addEventListener('resize', () => {
    trendInstance.resize()
    categoryInstance.resize()
  })
})

// 获取仪表盘数据
const fetchDashboardData = async () => {
  const { data } = await getDashboardData({
    timeType: timeRange.value,
    dateRange: dateRange.value as [string, string]
  })
  dashboardData.value = data
  renderCharts()
}

// 处理时间范围切换
const handleTimeRangeChange = (value: 'month' | 'year') => {
  // renderTrendChart(value)
  timeRange.value = value
  fetchDashboardData()
}

// 处理日期选择
const handleDateChange = (dates: [string, string]) => {
  console.log('日期范围变更:', dates)
  dateRange.value = dates
  fetchDashboardData()
}

// 渲染图表
const renderCharts = () => {
  if (!dashboardData.value) return
  
  renderTrendChart()
  renderCategoryChart()
}

// 渲染趋势图（严格匹配图片数据）
const renderTrendChart = () => {
  // const option = {
  //   tooltip: {
  //     trigger: 'axis',
  //     formatter: '{b}<br/>销售额: {c}元'
  //   },
  //   xAxis: {
  //     type: 'category',
  //     data: type === 'month' 
  //       ? ['1月', '2月', '3月', '4月', '5月', '6月', '7月', '8月', '9月', '10月', '11月', '12月']
  //       : ['2022年', '2023年', '2024年'],
  //     axisLine: {
  //       lineStyle: {
  //         color: '#999'
  //       }
  //     },
  //     axisTick: {
  //       alignWithLabel: true
  //     }
  //   },
  //   yAxis: {
  //     type: 'value',
  //     name: '元',
  //     min: 0,
  //     max: type === 'month' ? 250 : 3000,
  //     interval: type === 'month' ? 50 : 500,
  //     axisLine: {
  //       show: true,
  //       lineStyle: {
  //         color: '#999'
  //       }
  //     },
  //     splitLine: {
  //       lineStyle: {
  //         type: 'dashed'
  //       }
  //     }
  //   },
  //   series: [{
  //     data: type === 'month' ? monthlyData : yearlyData,
  //     type: 'line',
  //     smooth: true,
  //     symbol: 'circle',
  //     symbolSize: 8,
  //     lineStyle: {
  //       width: 3,
  //       color: '#5470c6'
  //     },
  //     itemStyle: {
  //       color: '#5470c6',
  //       borderWidth: 2
  //     },
  //     areaStyle: {
  //       color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [
  //         { offset: 0, color: 'rgba(84, 112, 198, 0.5)' },
  //         { offset: 1, color: 'rgba(84, 112, 198, 0.1)' }
  //       ])
  //     }
  //   }],
  //   grid: {
  //     left: '3%',
  //     right: '4%',
  //     bottom: '3%',
  //     containLabel: true
  //   }
  // }
  // trendInstance.setOption(option)
  const data = timeRange.value === 'month' 
    ? dashboardData.value!.monthlySales 
    : dashboardData.value!.yearlySales
  
  const option = {
    tooltip: {
      trigger: 'axis',
      formatter: '{b}<br/>销售额: {c}元'
    },
    xAxis: {
      type: 'category',
      data: data.map(item => item.timeLabel),
      axisLine: { lineStyle: { color: '#999' } },
      axisTick: { alignWithLabel: true }
    },
    yAxis: {
      type: 'value',
      name: '元',
      min: 0,
      max: timeRange.value === 'month' ? 250 : 3000,
      interval: timeRange.value === 'month' ? 50 : 500,
      axisLine: { show: true, lineStyle: { color: '#999' } },
      splitLine: { lineStyle: { type: 'dashed' } }
    },
    series: [{
      data: data.map(item => item.amount),
      type: 'line',
      smooth: true,
      symbol: 'circle',
      symbolSize: 8,
      lineStyle: { width: 3, color: '#5470c6' },
      itemStyle: { color: '#5470c6', borderWidth: 2 },
      areaStyle: {
        color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [
          { offset: 0, color: 'rgba(84, 112, 198, 0.5)' },
          { offset: 1, color: 'rgba(84, 112, 198, 0.1)' }
        ])
      }
    }],
    grid: {
      left: '3%',
      right: '4%',
      bottom: '3%',
      containLabel: true
    }
  }
  trendInstance.setOption(option)
}

// 渲染分类环形图
const renderCategoryChart = () => {
  const option = {
    tooltip: {
      trigger: 'item',
      formatter: '{b}: {c}元 ({d}%)'
    },
    legend: {
      orient: 'vertical',
      right: 10,
      top: 'center',
      data: dashboardData.value!.categorySales.map(item => item.categoryName),
      textStyle: {
        fontSize: 12
      }
    },
    series: [{
      name: '销售额',
      type: 'pie',
      radius: ['50%', '70%'],
      center: ['40%', '50%'],
      avoidLabelOverlap: false,
      label: {
        show: false,
        position: 'center'
      },
      emphasis: {
        label: {
          show: true,
          fontSize: '18',
          fontWeight: 'bold'
        }
      },
      labelLine: {
        show: false
      },
      data: dashboardData.value!.categorySales.map(item => ({
        value: item.amount,
        name: item.categoryName,
        itemStyle: { color: getCategoryColor(item.categoryId) }
      }))
    }]
  }
  categoryInstance.setOption(option)
}

// 获取分类颜色
const getCategoryColor = (categoryId: number) => {
  const colors = ['#FF6384', '#36A2EB', '#FFCE56', '#4BC0C0', '#9966FF']
  return colors[categoryId % colors.length]
}
</script>

<style scoped>
.dashboard-container {
  display: flex;
  justify-content: center;
  align-items: center;
  min-height: 90vh;
  padding: 20px;
  background: white;
}

.chart-row {
  display: flex;
  gap: 40px;
  width: 95%;
  max-width: 1600px;
}

.chart-card {
  flex: 1;
  min-width: 700px;
  border-radius: 8px;
  padding: 30px;
  background: white;
  box-shadow: 0 4px 16px rgba(0,0,0,0.08);
  display: flex;
  flex-direction: column;
  height: 700px;
}

/* 折线图头部样式 */
.chart-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

/* 分类图头部样式 */
.right-chart h3 {
  margin-bottom: 15px;
}

.date-picker-container {
  margin-bottom: 20px;
  display: flex;
  justify-content: flex-end;
}

.time-select {
  width: 120px;
}

.time-select :deep(.el-input__inner) {
  border-color: #F56C6C;
}

.date-picker {
  width: 280px;
}

.chart {
  flex: 1;
  min-height: 600px;
}

h3 {
  font-size: 20px;
  margin: 0;
  color: #333;
  display: flex;
  align-items: center;
}

.unit {
  font-size: 14px;
  color: #999;
  margin-left: 12px;
  font-weight: normal;
}

@media (max-width: 1800px) {
  .chart-card {
    min-width: 600px;
    height: 650px;
  }
  .chart {
    min-height: 550px;
  }
}

@media (max-width: 1400px) {
  .chart-row {
    flex-direction: column;
    align-items: center;
  }
  .chart-card {
    width: 90%;
    min-width: auto;
    margin-bottom: 40px;
  }
  
  .date-picker {
    width: 220px;
  }
}
</style>